package com.customization.unionpay.market.workflowaction;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.maketEnum.InstructionEnum;
import com.customization.unionpay.market.util.ClearFundButtonRelated;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.contract.serivce.impl.ContractBaseServiceImpl;
import com.customization.unionpay.market.util.MPManagePlatformUtils;
import com.customization.unionpay.market.util.PropUtils;
import weaver.generalledger.action.ZzgdExecuteInstrucitonAction;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.util.Map;

/**
 * @author sjm
 * @description 营销事项申请表单节点(归档)action
 */
public class MarketingApplicationChangeEndAction implements Action {

    private static final Logger log = LoggerFactory.getLogger(MarketingApplicationChangeEndAction.class);

    @Override
    public String execute(RequestInfo requestInfo) {

        RequestManager rm = requestInfo.getRequestManager();
        try {

            // 营销活动事项台账表单id
            int activityLedgerFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_ledger_form_id"));
            String activityLedgerTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(activityLedgerFormId);

            ContractBaseServiceImpl contractBaseService = new ContractBaseServiceImpl();
            // 流程表单id
            int formId = rm.getFormid();

            Map<String, Object> allFormData = com.customization.unionpay.market.util.FormDataUtils.getAllFormData(requestInfo);

            Map<String, String> mainMap = (Map<String, String>) allFormData.get("mainMap");
            // 所有明细表的值
            Map<String, Map<String, Map<String, String>>> detailMap = (Map<String, Map<String, Map<String, String>>>) allFormData.get("detailMap");
            // 主 业务类型        ywlx
            String ywlx = mainMap.get("ywlx");
            String ywlxName = com.customization.unionpay.market.util.FormDataUtils.getItemName(formId,"ywlx",ywlx);
            log.info("业务类型："+ywlxName);

            String bdh = mainMap.get("bdh");
            log.info("bdh：" + bdh);

            // 【本次调整金额】写入合同明细行【已付款（含SQ申请）金额】，金额调增单需扣减【审批中金额】 1 提交 2 回退 3 归档 4、本次调整金额
            if("营销平台事项申请金额调增单".equals(ywlxName)) {
                // 调增正数
                Map<String, Map<String, String>> dt1 = detailMap.get("dt1");
                for (String key : dt1.keySet()) {
                    Map<String, String> value = dt1.get(key);
                    // 本次调整金额
                    String bcdzje = value.get("bcdzje");
                    // 履约明细号
                    Integer lymxh = Integer.valueOf(value.get("lymxh"));
                    log.info("lymxh：" + lymxh);
                    contractBaseService.updateAmountFunded(3, lymxh, bcdzje);
                }
            }
            if("营销平台事项申请金额调减单".equals(ywlxName)) {
                // 调减单负数
                Map<String, Map<String, String>> dt1 = detailMap.get("dt1");
                for (String key : dt1.keySet()) {
                    Map<String, String> value = dt1.get(key);
                    // 本次调整金额
                    String bcdzje = value.get("bcdzje");
                    // 履约明细号
                    Integer lymxh = Integer.valueOf(value.get("lymxh"));
                    log.info("lymxh：" + lymxh);
                    String fbcdzje = String.valueOf((Double.parseDouble(bcdzje) * -1));
                    log.info("fbcdzje：" + fbcdzje);
                    contractBaseService.updateAmountFunded(3, lymxh, fbcdzje);
                }
            }

            // 主 业务日期        ywrq
            String ywrq = mainMap.get("ywrq");
            log.info("ywrq:" + ywrq);
            // 主 预算控制期      yskzq
            String yskzq = mainMap.get("yskzq");
            log.info("yskzq:" + yskzq);

            // 流程标题
            String requestName = requestInfo.getDescription();
            String tableName = rm.getBillTableName();          // 表单名称
            log.info("tableName:" + tableName);

            String ywrqStr = com.customization.unionpay.market.util.FormDataUtils.changeDateString("yyyy-MM-dd", ywrq, "yyyy");
            String yskzqStr = com.customization.unionpay.market.util.FormDataUtils.changeDateString("yyyy-MM-dd", yskzq, "yyyy");

            String requestid = String.valueOf(rm.getRequestid());

            // sfwdxy   是否为大协议
            String sfwdxy = mainMap.get("sfwdxy");
            String sfwdxyName = com.customization.unionpay.market.util.FormDataUtils.getItemName(formId, "sfwdxy", sfwdxy);
            log.info("是否为大协议："+sfwdxyName);

            String ysxsqdh = mainMap.get("ysxsqdh");
            log.info("ysxsqdh：" + ysxsqdh);

            String sqdh = com.customization.unionpay.market.util.FormDataUtils.selectMarketingActivityLedgerById(activityLedgerTableName, ysxsqdh);
            log.info("sqdh："+sqdh);
            
            if("否".equals(sfwdxyName)) {
                if ("营销平台事项申请金额调减单".equals(ywlxName)) {
                    log.info("提交预算营销平台事项申请金额调减单！");
                    com.customization.unionpay.market.workflowaction.MarketingApplicationChangeAction marketingApplicationChangeAction = new MarketingApplicationChangeAction();
                    JSONObject params = new JSONObject();
                    String instruction = "";
                    if (ywrqStr.equals(yskzqStr)) {
                        // 预算 业务日期的年份=预算控制期的年份  提交-释放占用
                        params = marketingApplicationChangeAction.getMarketingApplicationChangeAddMiddle(requestName, yskzq, yskzqStr, mainMap, detailMap, sqdh, bdh, tableName, requestid);
                        instruction = com.customization.unionpay.market.maketEnum.InstructionEnum.SFZY.toString();
                    } else {
                        // 预算 业务日期的年份≠预算控制期的年份  提交-项目释放占用
                        params = marketingApplicationChangeAction.getMarketingApplicationChangeAddMiddle(requestName, yskzq, yskzqStr, mainMap, detailMap, sqdh, bdh, tableName, requestid);
                        instruction = InstructionEnum.XMSFZY.toString();
                    }
                    log.info("预算校验拼接参数：" + params);
                    int yszjbFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "yszjb_form_id"));
                    int yszjbFormmodeId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "yszjb_formmode_id"));
                    String yszjbTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(yszjbFormId);
                    log.info("yszjbTableName：" + yszjbTableName);
                    String bId = com.customization.unionpay.market.util.FormDataUtils.addYuMiddleForm(yszjbFormId, yszjbFormmodeId, yszjbTableName, rm.getUser(), params);

                    log.info("instruction：" + instruction);
                    ZzgdExecuteInstrucitonAction zzgdExecuteInstrucitonAction = new ZzgdExecuteInstrucitonAction();
                    zzgdExecuteInstrucitonAction.setZl(instruction);
                    String execute = zzgdExecuteInstrucitonAction.execute(requestInfo);
                    if ("0".equals(execute)) {
                        if (bId != null && !"".equals(bId)) {
                            ClearFundButtonRelated.deleteByBillId(yszjbTableName, Integer.parseInt(bId));
                        }
                        String messageid = requestInfo.getRequestManager().getMessageid();
                        log.info("messageid：" + messageid);
                        String messagecontent = requestInfo.getRequestManager().getMessagecontent();
                        log.info("messagecontent：" + messagecontent);
                        return Action.FAILURE_AND_CONTINUE;
                    } else {
                        log.info("预算调用成功！");
                    }
                }
            }

            // 营销平台活动授权码
            String authCode = mainMap.get("yxpthdsqm");
            if (StrUtil.isNotBlank(authCode)) {
                // 判斷是否是营销项目管理平台发起了
                // 来源系统
                String lyxt = mainMap.get("lyxt");
                log.info("lyxt："+lyxt);
                if(lyxt != null && !"".equals(lyxt)) {
                    String projectCode = mainMap.get("project_code");
                    String bcdzje = mainMap.get("bcdzje");
                    String bcdzjeToWanYuan = FormDataUtils.changeYuanToWanYuan(bcdzje);
                    log.info("本次调整金额:" + bcdzjeToWanYuan);
                    // 审批结果
                    String auditMessage = "审核通过";

                    // 更新项目管理平台
                    String result = MPManagePlatformUtils.applicationChangeProcessPush(bdh, authCode, projectCode, bcdzjeToWanYuan, auditMessage);
                    log.info("推送营销项目管理平台调整金额返回值：" + result);

                    JSONObject resultJson = JSONObject.parseObject(result);
                    String code = resultJson.getString("code");

                    if (!"200".equals(code)) {
                        String message = resultJson.getString("message");
                        log.error("请求失败：" + message);
                        requestInfo.getRequestManager().setMessageid("10001");
                        requestInfo.getRequestManager().setMessagecontent("营销平台活动授权码：" + authCode + "相关信息，推送营销项目管理平台调整金额失败：" + message);
                        return Action.FAILURE_AND_CONTINUE;
                    }
                }else {
                    log.info("当前调整单不是营销项目管理平台发起，不需要推送营销项目管理平台！");
                }
            } else {
                requestInfo.getRequestManager().setMessageid("10001");
                requestInfo.getRequestManager().setMessagecontent("营销平台活动授权码不能为空！");
                return Action.FAILURE_AND_CONTINUE;
            }
        } catch (Exception e) {
            // 异常报错是填写异常信息，阻止流程继续流转
            requestInfo.getRequestManager().setMessageid("10001");
            requestInfo.getRequestManager().setMessagecontent(e.getMessage());
            return Action.FAILURE_AND_CONTINUE;
        }
        return Action.SUCCESS;
    }
}
